package mediaitem;

import java.io.*;
import java.util.ArrayList;
import collection.Collection;
import java.util.Scanner;

public class MediaItem {
	private String itemName;
	private String itemDescription;
	private String itemPath;
	private String itemType;
	private ArrayList<Collection> collections = null;	// list of Collections that contains item
	
	public MediaItem(String name, String description, String path){
        this.itemName = name;
		this.itemDescription = description;
		
		File inFile = new File(path);
		if(!inFile.exists())
			throw new IllegalArgumentException("No such file " + path +".Please check your path");
		this.itemPath = path;
		
		// determine file type
		String extension = path.substring((path.lastIndexOf('.')+1));
		try{
			inFile = new File("this.itemType.txt");  // traverse through a list of extensions with associated file types:Audio, Video, Image, Document
			Scanner in = new Scanner(inFile);
			String tmp;
			while(in.hasNext()){
				if(in.hasNext(extension)){
					tmp = in.nextLine();
					this.itemType = tmp.substring(tmp.lastIndexOf(' ')+1);;
					break;
				}
				else
					in.nextLine();
			}
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
	}
	
	public boolean updateDescription(String newDescription){
		this.itemDescription = newDescription;
		return true;
	}
	
	public boolean updateName(String newName){
		this.itemName = newName;
		return true;
	}

    public boolean updatePath(String newPath){
    	boolean returnValue = true;
        File inFile = new File(newPath);
        
		if(!inFile.exists()){
			throw new IllegalArgumentException("No such file " + newPath +".Please check your path");
        }
		this.itemPath = newPath;
		
		// determine file type
		String extension = newPath.substring((newPath.lastIndexOf('.')+1));
        if(extension.equals(this.itemType))
            return true;

		try{
			inFile = new File("this.itemType.txt");
			Scanner in = new Scanner(inFile);
			String tmp;
			while(in.hasNext()){
				if(in.hasNext(extension)){
					tmp = in.nextLine();
					this.itemType = tmp.substring(tmp.lastIndexOf(' ')+1);;
					break;
				}
				else
					in.nextLine();
			}
		}catch(IOException ioe){
			ioe.printStackTrace();
            returnValue = false;
		}
        return returnValue;
    }

	public String getName() {
		return itemName;
	}
	
	public String getDescription(){
		return itemDescription;
	}
	
	public String getPath(){
		return itemPath;
	}
	
	public String getType(){
		return itemType;
	}
	
	public boolean addCollection(Collection col){
		return collections.add(col);
	}
	
    public boolean removeCollection(Collection col){
    	return collections.remove(col);
    }
    
	public boolean removeFromAll() {
		boolean returnValue = true;
		
		for (Collection coll : this.collections){
			returnValue = coll.removeMediaItem(this);
		}
		collections = null;
		
		return returnValue;
	}
}
